import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getAccessToken, getRefreshToken } from '@/utils/auth'
import Qs from 'qs'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间,
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.access_token) {
      config.headers['Authorization'] = getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    // 判断是否为formData形式 不是则转为字符串
    if (config.method === 'post' && Object.prototype.toString.call(config.data) !== '[object FormData]') {
      config.data = Qs.stringify(config.data)
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code === 200) {
      return response.data
    } else {
      if (res.code === 50014) { // 请求刷新token
        return new Promise(resolve => {
          var config = response.config
          config.headers.Authorization = getRefreshToken()
          axios.request(config).then((res) => {
            if(res.data.code===50015){ //处理刷新的token
              let newtoken = res.data.data
              store.dispatch('restToken', newtoken).then(() => {
                var config = response.config
                config.headers.Authorization = newtoken.access_token
                axios.request(config).then((res) => {
                  resolve(res.data)
                })
              })
            }else{
              resolve(res.data)
            }
          })
        })
      } else if (res.code === 50008 || res.code === 50012) {
        MessageBox.confirm(
          '안전을 위해 다시 로그인 하십시오',
          '로그아웃',
          {
            confirmButtonText: '로그인',
            cancelButtonText: '취소',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        return res
      } else {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
        return res
      }
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
